package com.awei.study.design.found.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * 改造简单工厂方法
 */
public class SimpleFactory {
    private static Map<String , Coffee> objectMap = new HashMap<>();

    static {
        Properties p = new Properties();

        InputStream is = SimpleFactory.class.getClassLoader().getResourceAsStream("bean.properties");

        try {
            p.load(is);
            Set<Object> keys = p.keySet();
            for (Object key : keys) {
                String property = p.getProperty((String) key);
                System.out.println(property);
                Class<?> aClass = Class.forName(property);
                Coffee coffee = (Coffee) aClass.newInstance();
                objectMap.put((String) key,coffee);
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    public static Coffee getCoffee(String name) {
        return objectMap.get(name);
    }

    public static void main(String[] args) {
        Coffee chinaCoffee = getCoffee("ChinaCoffee");
        chinaCoffee.add();
        chinaCoffee.big();
    }

}
